package sqlplus;

import java.sql.*;
import java.io.*;

public class Lab15 {
	public static void main(String[] args) {
		if (args.length != 1) {
			System.out.println("用法:java Lab15 文件名");
			return;
		}
		Connection con = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		Blob blob = null;
		int id = 1;
		String fileName = args[0];
		try {
			con = JdbcUtil.getConn();
			con.setAutoCommit(false);
			// 1.委托oracle替我们制造一个空的blob对象
			String sql = "insert into t_blob " + "values(?,?,empty_blob())";
			ps = con.prepareStatement(sql);
			ps.setInt(1, id);
			ps.setString(2, fileName);
			ps.executeUpdate();
			// 2.将空的blob对象读出来
			sql = "select FILE_CONTENT from " + "t_blob where ID=? for update";		//for update为了防止其他的来读取。
			JdbcUtil.close(null, ps, null);
			ps = con.prepareStatement(sql);
			ps.setInt(1, id);
			rs = ps.executeQuery();
			if (rs.next()) {
				blob = rs.getBlob(1);
			}
			// 3.将文件中的内容导入到blob对象中
			InputStream in = new FileInputStream(fileName);
			OutputStream out = blob.setBinaryStream(0);
			byte[] content = new byte[in.available()];	//得到可变长度。
			in.read(content);
			out.write(content);
			in.close();
			out.close();
			// 4.将blob对象更新回数据库
			sql = "update t_blob " + "set FILE_CONTENT=?" + " where ID=?";
			JdbcUtil.close(rs, ps, null);
			ps = con.prepareStatement(sql);
			ps.setBlob(1, blob);
			ps.setInt(2, id);
			ps.executeUpdate();
			con.commit();

		} catch (Exception e) {
			e.printStackTrace();
			try {
				con.rollback();
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		} finally {
			JdbcUtil.close(null, ps, con);
		}
	}
}
